<template>
    <li>
        <label>
            <input type="checkbox" :checked="todo.completed" @click="updateStatus(todo.id)"/>
            <!-- 不推荐下面这种写法 -->
            <!-- <input type="checkbox" v-model="todo.completed"/> -->
            <span v-show="!todo.isEdit">{{todo.title}}</span> 
            <input type="text" 
            ref="inutTitle"
            v-show="todo.isEdit" 
            :value="todo.title" 
            @keyup.enter="handleBlur(todo, $event)"
            @blur="handleBlur(todo, $event)"/>
        </label>
        <button class="btn btn-danger" @click="deleteTodoById(todo.id)">删除</button>
        <button class="btn btn-edit" v-show="!todo.isEdit" @click="handleUpdate(todo)">编辑</button>
    </li>
</template>

<script>
export default {
    name: 'TodoItem',
    //声明接收父组件传递过来的数据todo对象
    props: ['todo'],
    mounted() {
        // console.log(this.todo)
    },
    methods: {
      updateStatus(id){
        //使用$bus总线机制，通知父组件更新todo状态
        this.$bus.$emit('updateTodoStatus', id)
      },
      deleteTodoById(id){
        console.log(id)
        this.$bus.$emit('deleteTodo', id)
      },
      handleUpdate(todo){
        todo.isEdit = true
        //如果todo里面没有isEdit属性，就添加一个
/*         if(!todo.hasOwnProperty('isEdit')){
          this.$set(todo, 'isEdit', true)
        } */
        //读取输入框
/*         setInterval(() => {
          this.$refs.inutTitle.focus()
        }, 200); */

        this.$nextTick(() => {
          this.$refs.inutTitle.focus()
        })
      },
      handleBlur(todo,event){
        // console.log(this.todo)
        const newTodo = {
          id: this.todo.id,
          title: event.target.value,
          completed: this.todo.completed,
          isEdit: false
        }
        if(newTodo.title.trim().length === 0){
          //如果用户输入的内容为空
          return alert('输入不能为空')
        }
        this.$bus.$emit('updateTodo', newTodo)
      }
    },

}
</script>

<style scoped>
/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

li:hover {
  background: #aeefc1;
}
li:hover button {
  display:block;
}

</style>